Leetcode JS 2676. Throttle


Posted by Lucy on 2023-06-01

我總覺得我把這題想得很複雜,有錯歡迎指證
Given a function fn and a time in milliseconds t, return a throttled version of that function.
A throttled function is first called without delay and then, for a time interval of t milliseconds, can't be executed but should store the latest function arguments provided to call fn with them after the end of the delay.

這題其實花了一段時間,還查了一下看了別人怎麼解,不過都過不了(笑,最後還是自己思考了一下才大概解出來的,果然還是要自己想比較好,思路直接寫在註解上。

/**
 * @param {Function} fn
 * @param {number} t
 * @return {Function}
 */
var throttle = function(fn, t=500) {
    let timer=null;
    let nextExceTime=0;//下次可執行時間
  return function(...args) {
      let nowTime=new Date().getTime();
      //第一次直接執行
      if(nextExceTime===0){
        nextExceTime=nowTime+t;//下次執行時間會是目前時間+t秒
        fn.apply(this,args)
        return
      }
      const delay=nextExceTime-nowTime//實際延遲的時間,負數的話同於0
        clearTimeout(timer)//如果重複執行的話就先清除重新計時,假設短時間內執行兩次會以後面那次為主
        timer=setTimeout(()=>{
              clearTimeout(timer)//執行完清除,應該跟timer=null兩者擇一即可
              timer=null
               nextExceTime=new Date().getTime()+t //因為我實際計時時間是實際延遲的時間,所以這邊下次可執行時間必須+t
               fn.apply(this,args)
          },delay)
  }
};

#Leetcode







Related Posts

MTR04_0629

MTR04_0629

CSS換行語法 學習筆記

CSS換行語法 學習筆記

 網站部署 --AWS EC2 雲端主機 + LAMP Server + phpMyAdmin

網站部署 --AWS EC2 雲端主機 + LAMP Server + phpMyAdmin


Comments